package fr.utbm.gi.in56.ads;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.utbm.gi.in56.error.ErrorType;

/**
 * Servlet implementation class SearchAdServlet
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet( "/SearchAdServlet" )
public class SearchAdServlet extends AdServlet
{
	private static final long	serialVersionUID	= 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SearchAdServlet()
	{
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		request.setCharacterEncoding( "UTF-8" ); //$NON-NLS-1$
		
		ErrorType result = forwardEnergyAndCarLists( request, response );
		if ( result != ErrorType.NONE )
		{
			request.setAttribute( "error", result ); //$NON-NLS-1$
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp"); //$NON-NLS-1$
			rd.forward( request, response );
			return;
		}
		
		String adType = request.getParameter( "adType" );
		if ( adType.compareTo( "sell" ) == 0 )
		{
			AdsManager adsMg = new AdsManager( getConnection() );
			List< AdSell > adSellList = adsMg.getSellAds( 0, 0, 2, -1, -1, 0, 0,
					-1, -1, 0, 10, 0, false, AdState.OPENED.ordinal(), -1, 0, "", "" );
			
			request.setAttribute( "adSellList", adSellList ); //$NON-NLS-1$
			
			RequestDispatcher rd = request.getRequestDispatcher( "searchSellAd.jsp" ); //$NON-NLS-1$
			rd.forward( request, response );
			return;
		}
		else if( adType.compareTo( "buy" ) == 0 )
		{
			AdsManager adsMg = new AdsManager( getConnection() );
			List< AdBuy > adBuyList = adsMg.getBuyAds( 0, 0, 2, -1, 0, -1, 0,
					10, 0, false, -1, -1, 0, "", "" );
			
			request.setAttribute( "adBuyList", adBuyList ); //$NON-NLS-1$
			
			RequestDispatcher rd = request.getRequestDispatcher( "searchBuyAd.jsp" ); //$NON-NLS-1$
			rd.forward( request, response );
			return;
		}
	}
}
